#include <stdio.h>
#include <stdarg.h>
#include "communication/message.h"
#include "utils/logger.h"
#include "utils/utils.h"
static uint32_t level_data[2];
static char log_cache[128];
//static co_queue_t log_queue = NULL;
int can_fputc(char c);


static int _get_level(int mod){
	int index = mod_bit_start(mod)/(32+1);
	mod = mod_bit_start(mod) % 32;
	return (level_data[index] >> mod) & LEVEL_MASK;
}

void set_log_level(int mod, int l){
	int index = mod_bit_start(mod)/(32+1);
	mod = mod_bit_start(mod) % 32;
	level_data[index] = (level_data[index] & (~(LEVEL_MASK<<mod))) | ((l & LEVEL_MASK)<<mod);
}

static void log_out(char *fmt, va_list args){
	int len = vsnprintf(log_cache, sizeof(log_cache), fmt, args);
	for (int i = 0; i < len; i++) {
		can_fputc(log_cache[i]);
	}
}

void log_debug(int mod, char *fmt, ...){
	if (_get_level(mod) >= L_debug){
		va_list args;
		va_start(args, fmt);		
		log_out(fmt, args);
		va_end(args);
	}
}

void log_warning(int mod, char *fmt, ...){
	if (_get_level(mod) >= L_warning){
		va_list args;
		va_start(args, fmt);		
		log_out(fmt, args);
		va_end(args);
	}
}

void log_error(int mod, char *fmt, ...){
	if (_get_level(mod) >= L_error){
		va_list args;
		va_start(args, fmt);		
		log_out(fmt, args);
		va_end(args);
	}
}


static u8 log_buffer[64];
static int log_index = 0;
int can_fputc(char c){
	head_t frame_id;
	frame_id.id=0;
	frame_id.src 	= MY_MESSAGE_ADDR;
	frame_id.type 		= ptype_indicater;

	if (c == '\n'){ //don't send '\n'
		if (log_index != 0){
			frame_id.dest 	= 0x72;
			message_send(frame_id.id, log_buffer, log_index, 0);
		}
		log_index = 0;
	}else if (log_index == sizeof(log_buffer)){
		frame_id.dest 	= 0x70;
		message_send(frame_id.id, log_buffer, log_index, 0);
		log_index = 0;
		log_buffer[log_index++] = c;
	}else{
		log_buffer[log_index++] = c;
	}
	return 1;
}
